package com.test.security.a;

import cn.hutool.core.codec.Base64;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;

/**
 * @author: zouren
 * @date: 2022/3/8
 * @description: 使用私钥进行签名
 */
public class Signaturer {

    public static String sign(byte[] priKeyText, byte[] content) {
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(priKeyText));
            KeyFactory keyf = KeyFactory.getInstance("RSA");
            PrivateKey prikey = keyf.generatePrivate(priPKCS8);
            // 用私钥对信息生成数字签名
            Signature signet = java.security.Signature.getInstance("MD5withRSA");
            signet.initSign(prikey);
            signet.update(content);
            String signed = Base64.encode(signet.sign());
            return signed;
        } catch (java.lang.Exception e) {
            System.out.println("签名失败");
            e.printStackTrace();
        }
        return null;

    }
    public static String sign(byte[] priKeyText, String content) {
        return sign(priKeyText,content.getBytes());

    }
}
